package com.online.pay.common.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Json工具
 * @author Qiurz
 *
 */
public class JsonUtil {

	/**
	 * map转换json
	 * @param map
	 * @return
	 */
	public static String fromMapToJson(Map<String, String> map) {
		return JSON.toJSONString(map);
	}
	
	/**
	 * json转换map
	 * @param json
	 * @return
	 */
	public static Map<String, String> fromJsonToMap(String str) {
		Map<String, String> map = new HashMap<String, String>();
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			map = objectMapper.readValue(str, new TypeReference<HashMap<String, String>>(){});
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return map;
	}
	
	/**
	 * json转换类bean
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> T fromJsonToBean(String json,Class<T> clazz) {
		return JSON.parseObject(json, clazz);
	}
	
	/**
	 * bean类转换json
	 * @param obj
	 * @return
	 */
	public static String fromBeanToJson(Object obj) {
		return JSON.toJSONString(obj);
	}
	
	/**
	 * bean to map
	 * @param obj
	 * @return
	 */
	public static Map<String, String> transBean2Map(Object obj) {  
        if(obj == null){  
            return null;  
        }          
        Map<String, String> map = new HashMap<String, String>();  
        try {  
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
            for (PropertyDescriptor property : propertyDescriptors) {  
                String key = property.getName();  
                // 过滤class属性  
                if (!key.equals("class")) {  
                    // 得到property对应的getter方法  
                    Method getter = property.getReadMethod();  
                    String value = (String) getter.invoke(obj);  
                    map.put(key, value);  
                }  
            }  
        } catch (Exception e) {  
            System.out.println("transBean2Map Error " + e);  
        }  
        return map;  
  
    }  
}
